package pers.cz.filter;

import pers.cz.exception.ErrorCode;
import pers.cz.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;

/**
 * 权限管理决断器
 * @program: springSecurity
 * @description: CustomAccessDecisionManager
 * @author: Cheng Zhi
 * @create: 2021-04-18 00:01
 **/
@Service
public class CustomAccessDecisionManager implements AccessDecisionManager {

    Logger logger = LoggerFactory.getLogger(CustomAccessDecisionManager.class);
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if (collection == null) {
            return;
        }

        Iterator<ConfigAttribute> iterators = collection.iterator();
        while (iterators.hasNext()) {
            ConfigAttribute configAttribute = iterators.next();

            // 访问资源需要的权限
            String needRole = configAttribute.getAttribute();
            if ("ROLE_LOGIN".equals(needRole)) {
                // 如果是true表示未登录
                if (authentication instanceof AnonymousAuthenticationToken) {
                    //throw new BusinessException(ErrorCode.NO_POWER_REQUEST_ERROR);
                    // 匿名用户允许访问
                    logger.debug("匿名用户");
                    return;
                } else if(authentication instanceof UsernamePasswordAuthenticationToken){

                    // 正常登录用户
                    return;
                } else {
                    // 其他情况拦截
                    throw new BusinessException(ErrorCode.NO_LOGIN_REQUEST_ERROR);
                }
            }

            // 用户目前的权限
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needRole.equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
            throw new BusinessException(ErrorCode.NO_POWER_REQUEST_ERROR);

        }

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
